var duration;

function on_off (device, bridge, value, action)  {
    var xhr = null;
    if (window.XMLHttpRequest || window.ActiveXObject) { 
        if (window.ActiveXObject) {
            try { 
                xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
    }
    xhr.open("POST", "index.html", true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("device="+device+"&bridge="+bridge+"&value="+value+"&action="+action);
}

function mute (device, bridge, value, action) {
    var xhr = null;
    if (window.XMLHttpRequest || window.ActiveXObject) { 
        if (window.ActiveXObject) {
            try { 
                xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
    }
    xhr.open("POST", "index.html", true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("device="+device+"&bridge="+bridge+"&value="+value+"&action="+action);
}

function volume (device, bridge, value, action) {
    var xhr = null;
    if (window.XMLHttpRequest || window.ActiveXObject) { 
        if (window.ActiveXObject) {
            try { 
                xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
    }
    xhr.open("POST", "index.html", true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("device="+device+"&bridge="+bridge+"&value="+value+"&action="+action);
}

function changePreset (device, bridge, value, action) {
    var xhr = null;
    if (window.XMLHttpRequest || window.ActiveXObject) { 
        if (window.ActiveXObject) {
            try { 
                xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
    }
    xhr.open("POST", "index.html", true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("device="+device+"&bridge="+bridge+"&value="+value+"&action="+action);
}

function press (device, bridge, action) {
    var xhr = null;
    if (window.XMLHttpRequest || window.ActiveXObject) { 
        if (window.ActiveXObject) {
            try { 
                xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
    }
    xhr.open("POST", "index.html", true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("device="+device+"&bridge="+bridge+"&action="+action);
}

function seek (device, bridge, value, action) {
    var xhr = null;
    if (window.XMLHttpRequest || window.ActiveXObject) { 
        if (window.ActiveXObject) {
            try { 
                xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
    }
    xhr.open("POST", "index.html", true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("device="+device+"&bridge="+bridge+"&value="+value+"&action="+action);
}

function changeServer (value, action) {
    var xhr = null;
    if (window.XMLHttpRequest || window.ActiveXObject) { 
        if (window.ActiveXObject) {
            try { 
                xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
    }
    xhr.open("POST", "index.html", true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("value="+value+"&action="+action);
}

//______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
//Return a XMLHttpRequest
//______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
function getXMLHttpRequest() {
    var xhr = null;
	
    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    }else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
        return null;
    }
	
    return xhr;
}

//______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
//Loop which create a XMLHttpRequest and wait for the response
//then call recursivly the method
//______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

(function getAjax(){
    var xhr = getXMLHttpRequest();
    xhr.onreadystatechange=function(){
        if (xhr.readyState==4 && xhr.status==200){
            repaint(xhr.responseText);
            getAjax();
        }
    };
    xhr.open('POST','ajax',true);
    xhr.send();
})();

function repaint(HttpResponse){
    var split_rep = HttpResponse.split("/", 20);
    
    if(split_rep[3] == "LastChange"){
        if(split_rep[5] == "PLAYING"){
            document.getElementById('play_btn').setAttribute('src', 'html\\playDown.png');
            document.getElementById('pause_btn').setAttribute('src', 'html\\pause.png');
            document.getElementById('stop_btn').setAttribute('src', 'html\\stop.png');
            play_pb();
        }else if(split_rep[5] == "PAUSED"){
            document.getElementById('play_btn').setAttribute('src', 'html\\play.png');
            document.getElementById('pause_btn').setAttribute('src', 'html\\pauseDown.png');
            document.getElementById('stop_btn').setAttribute('src', 'html\\stop.png');
            pause_pb();
        }else if(split_rep[5] == "STOPPED"){
            document.getElementById('play_btn').setAttribute('src', 'html\\play.png');
            document.getElementById('pause_btn').setAttribute('src', 'html\\pause.png');
            document.getElementById('stop_btn').setAttribute('src', 'html\\stopDown.png');
            stop_pb();
        }else if(split_rep[4] == "mute"){
            var id, bridge;
            g_metadata = document.getElementsByTagName("meta");
            var len = g_metadata.length;
            for (var j = 0; j < len; j++) {
                if (g_metadata[j].name == 'uid') 
                    id = g_metadata[j].content;
                if (g_metadata[j].name == 'bridge') 
                    bridge = g_metadata[j].content;
            }
            if(split_rep[5] == "false"){
                document.getElementById('mute_btn').setAttribute('src', 'html\\volume.png');
                document.getElementById('mute_cmd').setAttribute('onClick', 'mute("' + id + '","' + bridge + '","true", "SET_MUTE");');                
            }else if(split_rep[5] == "true"){
                document.getElementById('mute_btn').setAttribute('src', 'html\\volumeDown.png');
                document.getElementById('mute_cmd').setAttribute('onClick', 'mute("' + id + '","' + bridge + '","false", "SET_MUTE");');   
            }
        }else if(split_rep[4] == "duration"){
            var split = split_rep[5].split(':', 3);
            var sbh = split[0]*3600;
            var sbm = split[1]*60;
            duration = sbh + sbm + split[2];
            document.getElementById('duration').innerHTML = split_rep[5];
        }else if(split_rep[4] == "vol"){
            document.getElementById('vol_b').setAttribute('value', split_rep[5]);
        }else if(split_rep[4] == "title"){
            document.getElementById('title_l').innerHTML = split_rep[5];
        }/*else if(split_rep[4] == "preset"){
            
        }*/else{
            window.location.reload(); //Repaint all 
        }
    }/*else if(split_rep[3] == "status"){
        document.getElementById(resp.substring(0,i-1)).setAttributeNS('http://www.w3.org/1999/xlink','xlink:href', 'html/img/'+split[2]);
    }*/else{        
        window.location.reload(); //Repaint all 
    }
    console.log("Response "+ HttpResponse);     
}

var progress;
var t;

function play_pb(){
    progress = $('#time').progressbar('option', 'value'); // récupération de la valeur actuelle
    if(progress < 100){
        console.log("duration "+duration);
        var new_progress= 100.0/duration;
        $('#time').progressbar('option', 'value', progress + new_progress); // on incrémente la valeur de 1 si elle est strictement inférieure à 100
        var current_perc = parseInt(progress + new_progress); //Recupération de la partie entière du pourcentage de lecture
        var current_sec = current_perc*duration/100;
        var hour = current_sec / 3600;
        var min = (current_sec % 3600) / 60;
        var sec = (current_sec % 3600) % 60;
        document.getElementById('time_l').innerHTML = parseInt(hour)+":"+parseInt(min)+":"+parseInt(sec);
        t=setTimeout('play_pb()', 1000);
    }
}

function pause_pb(){
    // mettre en pause
    clearTimeout(t);
    progress = $('#time').progressbar('option', 'value'); // récupération de la valeur actuelle            
}

function stop_pb(){
    //arreter la lecture du fichier audio
    clearTimeout(t);
    progress =0;
    $("#time").progressbar({
        value: progress
    });
                
}   

function findPos(el) {
    var x = 0;
    var y = 0;    
    if(el.offsetParent) {    
        //x = el.offsetLeft;    
        //y = el.offsetTop;    
        while(el == el.offsetParent) {    
            x += el.offsetLeft;    
            y += el.offsetTop;    
        }    
    }    
    return {
        'x':x, 
        'y':y
    };    
}

$(function() {
    $( "#time" ).progressbar();
                
    $("#time").click(function(event){
        var pos = findPos(this);      
        var diffx = event.layerX - pos.x; 
        var v = diffx*100/$(this).width();
        var id, bridge;
        g_metadata = document.getElementsByTagName("meta");
        var len = g_metadata.length;
        for (var j = 0; j < len; j++) {
            if (g_metadata[j].name == 'uid') 
                id = g_metadata[j].content;
            if (g_metadata[j].name == 'bridge') 
                bridge = g_metadata[j].content;
        }
        seek(id, bridge, v, "SEEK");
        $("#time").progressbar({
            value:v 
        });
        var duration = document.getElementById('duration').innerHTML;
        var current_sec = v*duration/100;
        var hour = current_sec / 3600;
        var min = (current_sec % 3600) / 60;
        var sec = (current_sec % 3600) % 60;
        document.getElementById('time_l').innerHTML = parseInt(hour)+":"+parseInt(min)+":"+parseInt(sec);
    });             
});